﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EShop.DataAccess;
using fastJSON;
using EShop.BussinessObjects;
using Mabna.Total.BOHelper;
using EShop.Common;
using EShop.BusinessLogic;
using DbLinq.Data.Linq;


public partial class Order : BaseThemePage, ICallbackEventHandler
{
    private class OrderCalculated_DiscountShow : ObjectSerializer
    {
        public int ID;
        public int GroupingCode;
        public String Caption;
        public Decimal DiscountPrice;
    }

    private class OrderCalculated : ObjectSerializer
    {
        public Decimal MinOrderPrice;
        public Contact contact;
        public List<OrderCalculated_DiscountShow> discountShowList;
    }

    private Decimal DeliveryDistricts_MinOrderPrice
    {
        get
        {
            if (ViewState["DeliveryDistricts_MinOrderPrice"] == null)
                return 0;
            else
                return Convert.ToDecimal(ViewState["DeliveryDistricts_MinOrderPrice"]);
        }
        set { ViewState["DeliveryDistricts_MinOrderPrice"] = value; }
    }
    private Boolean IsCompanyOpen
    {
        get
        {
            if (ViewState["IsCompanyOpen"] == null)
                return false;
            else
                return Convert.ToBoolean(ViewState["IsCompanyOpen"]);
        }
        set { ViewState["IsCompanyOpen"] = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if ((!Page.IsCallback) && (!Page.IsPostBack))
        {
            int _companyID = CGlobalData.GetCurrentCompanyID();

            CompanyDeliveryDistrict companyDeliveryDistrict_Filter = new CompanyDeliveryDistrict();
            companyDeliveryDistrict_Filter.ID = (int)cnstDatabase.DBOperationResult.ValueIsNotEffective;
            companyDeliveryDistrict_Filter.Company = new Company();
            companyDeliveryDistrict_Filter.Company.ID = _companyID;

            if (CGlobalData.IsLoggedIn())
            {
                User user = CGlobalData.GetCurrentUser();
                Contact contact_Filter = new Contact();
                contact_Filter.ID = user.Contact.ID;
                List<Contact> contactList = CDAContact.Select(contact_Filter);
                if (contactList.Count > 0)
                    companyDeliveryDistrict_Filter.PostalCode = contactList.First().PostalCode;
            }
            else
                companyDeliveryDistrict_Filter.PostalCode = ((int)cnstDatabase.DBOperationResult.ValueIsNotEffective).ToString();
            
            List<CompanyDeliveryDistrict> companyDeliveryDistrict_List = CDACompanyDeliveryDistrict.Select(companyDeliveryDistrict_Filter);
            if (companyDeliveryDistrict_List.Count > 0)
                DeliveryDistricts_MinOrderPrice = companyDeliveryDistrict_List.Min(x => x.MinOrderPrice);
            else
                DeliveryDistricts_MinOrderPrice = 0;
            
            CompanyConstant companyConstant_Filter = new CompanyConstant();
            companyConstant_Filter.ID = (int)cnstDatabase.DBOperationResult.ValueIsNotEffective;
            companyConstant_Filter.Constants = new Constants();
            companyConstant_Filter.Constants.ID = cnstConstants.PayOption;
            companyConstant_Filter.Company = new Company();
            companyConstant_Filter.Company.ID = _companyID;
            List<CompanyConstant> companyConstantList = CDACompanyConstant.Select(companyConstant_Filter);

            string innerHtml = "";
            foreach (CompanyConstant _companyConstant in companyConstantList)
            {
                innerHtml += "<img style=\"margin:5px\" src=\"Graphics\\images\\PayOption\\" + _companyConstant.Value + ".png\"/>";
            }
            divPayOptions.InnerHtml = innerHtml;

            CompanyWorkingHour companyWorkingHour_Filter = new CompanyWorkingHour();
            companyWorkingHour_Filter.ID = (int)cnstDatabase.DBOperationResult.ValueIsNotEffective;
            companyWorkingHour_Filter.Company = new Company();
            companyWorkingHour_Filter.Company.ID = _companyID;
            companyWorkingHour_Filter.DayOfWeek = (int)DateTime.Now.DayOfWeek;
            List<CompanyWorkingHour> companyWorkingHourList = CDACompanyWorkingHour.Select(companyWorkingHour_Filter);

            IsCompanyOpen = false;
            if (companyWorkingHourList.Count > 0)
            {
                if ((companyWorkingHourList.First().FromHour.TimeOfDay.TotalSeconds <= DateTime.Now.TimeOfDay.TotalSeconds) &&
                    (companyWorkingHourList.First().ToHour.TimeOfDay.TotalSeconds >= DateTime.Now.TimeOfDay.TotalSeconds))
                    IsCompanyOpen = true;
            }

            if (Request.QueryString["DayOfWeek"] != null)
            {
                int dayOfWeek = Convert.ToInt32(Request.QueryString["DayOfWeek"]);
                CompanyWeeklyMenu weeklyMenu_Filter = new CompanyWeeklyMenu();
                weeklyMenu_Filter.ID = (int)cnstDatabase.DBOperationResult.ValueIsNotEffective;
                weeklyMenu_Filter.Company = new Company();
                weeklyMenu_Filter.Company.ID = _companyID;
                weeklyMenu_Filter.DayOfWeek = dayOfWeek;
                List<CompanyWeeklyMenu> companyWeeklyMenuList = CDACompanyWeeklyMenu.Select(weeklyMenu_Filter);

                String scrpt = "var initialBasketItems = " + ObjectSerializer.ToJson(companyWeeklyMenuList) + ";";
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "initialBasketItems", scrpt, true);
            }
        

        }

        ProductCategory productCategory_Filter = new ProductCategory();
        productCategory_Filter.ID = ((int)cnstDatabase.DBOperationResult.ValueIsNotEffective);
        List<ProductCategory> cats = CDAProductCategory.Select(productCategory_Filter);
        string script = "var cats = " + ObjectSerializer.ToJson(cats) + ";";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "cats", script, true);

        Product product_Filter = new Product();
        product_Filter.ID = ((int)cnstDatabase.DBOperationResult.ValueIsNotEffective);
        product_Filter.IsActive = true;
        List<Product> products = CDAProduct.Select(product_Filter, true);
        foreach (Product product in products)
            product.Price = CBLProduct.CurrentPrice(product);
        script = "var products = " + ObjectSerializer.ToJson(products) + ";" ;
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "products", script, true);

        ProductExtra productExtra_Filter = new ProductExtra();
        productExtra_Filter.ID = ((int)cnstDatabase.DBOperationResult.ValueIsNotEffective);
        List<ProductExtra> productExtra = CDAProductExtra.Select(productExtra_Filter);
        script = "var productExtra = " + ObjectSerializer.ToJson(productExtra) + ";";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "productExtra", script, true);
        
        ProductShape productShape_Filter = new ProductShape();
        productShape_Filter.ID = ((int)cnstDatabase.DBOperationResult.ValueIsNotEffective);
        List<ProductShape> productShapes = CDAProductShape.Select(productShape_Filter);
        script = "var productShapes = " + ObjectSerializer.ToJson(productShapes) + ";";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "productShapes", script, true);
        
        script = "var deliveryDistricts_MinOrderPrice = '" + DeliveryDistricts_MinOrderPrice.ToString().Replace("," ,".") + "';";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "deliveryDistricts_MinOrderPrice", script, true);

        script = "var IsCompanyOpen = " + IsCompanyOpen.ToString().ToLower() + ";";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "IsCompanyOpen", script, true);

        if (!Page.IsCallback)
        {
            #region CallBack Scripts

            string cbReference =
                Page.ClientScript.GetCallbackEventReference(this,
                "arg", "OrderReceive", "context", true);

            string callbackScript;
            callbackScript = "function OrderCallServer(arg, context)" +
                "{" + cbReference + "} ;";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                "OrderCallServer", callbackScript, true);
            #endregion
        }

        Signup1.ClientEventafterInsert = "ContactInserted";
    }

    #region ICallbackEventHandler Members
    string CallBackResult = "";
    public string GetCallbackResult()
    {
        return CallBackResult;
    }

    public void RaiseCallbackEvent(string eventArgument)
    {
       
        string Command = eventArgument.Split('■')[0];
        string Data = eventArgument.Split('■')[1];
        if (Command == "GetContact")
        {
            if (!CGlobalData.IsLoggedIn())
                CallBackResult = "notLoggedIn■";
            else
                CallBackResult = "LoggedIn■" + CGlobalData.GetCurrentContactID();
            return;
        }
        else if (Command == "CalculateOrder")
        {
            OrderCalculated orderCalculated = new OrderCalculated();
            int _companyID = CGlobalData.GetCurrentCompanyID();

            OrderMaster orderMaster = (OrderMaster)ObjectSerializer.FromJson(Data, typeof(OrderMaster));
            
            Contact contact_Filter = new Contact();
            contact_Filter.ID = orderMaster.Contact.ID;
            List<Contact> contactList = CDAContact.Select(contact_Filter);
            if (contactList.Count > 0)
            {
                orderCalculated.contact = contactList[0];
                
                CompanyDeliveryDistrict companyDeliveryDistrict_Filter = new CompanyDeliveryDistrict();
                companyDeliveryDistrict_Filter.ID = (int)cnstDatabase.DBOperationResult.ValueIsNotEffective;
                companyDeliveryDistrict_Filter.Company = new Company();
                companyDeliveryDistrict_Filter.Company.ID = _companyID;
                companyDeliveryDistrict_Filter.PostalCode = orderCalculated.contact.PostalCode;
                
                List<CompanyDeliveryDistrict> companyDeliveryDistrict_List = CDACompanyDeliveryDistrict.Select(companyDeliveryDistrict_Filter);
                if (companyDeliveryDistrict_List.Count > 0)
                {
                    DeliveryDistricts_MinOrderPrice = companyDeliveryDistrict_List[0].MinOrderPrice;
                    orderCalculated.MinOrderPrice = DeliveryDistricts_MinOrderPrice;
                }
            }
            orderMaster.Company = new Company();
            orderMaster.Company.ID = _companyID;
        
            List<Discount> discountList = CBLDiscount.GetDiscounts(orderMaster);
            orderCalculated.discountShowList = new List<OrderCalculated_DiscountShow>();
            foreach (Discount discount in discountList)
            {
                OrderCalculated_DiscountShow discountShow = new OrderCalculated_DiscountShow();
                discountShow.ID = discount.ID;
                discountShow.GroupingCode = discount.GroupingCode;
                discountShow.DiscountPrice = 0;
                if (discount.DiscountDiscountElementID == cnstDiscountElement.Product)
                {
                    Product product_Filter = new Product();
                    product_Filter.ID = discount.DiscountDiscountElementValue;
                    List<Product> productList = CDAProduct.Select(product_Filter, false);
                    if (productList.Count > 0)
                        discountShow.Caption = discount.DiscountCount.ToInt64() + " " + productList.First().Name;
                }
                else if (discount.DiscountDiscountElementID == cnstDiscountElement.Euro)
                {
                    discountShow.Caption = discount.DiscountCount + " Euro";
                    discountShow.DiscountPrice = discount.DiscountCount;
                }
                else if (discount.DiscountDiscountElementID == cnstDiscountElement.Bonus)
                {
                    discountShow.Caption = discount.DiscountCount.ToInt64() + " Punkt(e)";
                }

                orderCalculated.discountShowList.Add(discountShow);
            }

            CallBackResult = "saveOrderCalculated■" + ObjectSerializer.ToJson(orderCalculated);
        }
        else if (Command == "InsertOrder")
        {
            int _companyID = CGlobalData.GetCurrentCompanyID();

            string ErrorMessage = "";
            OrderMaster orderMaster = (OrderMaster)ObjectSerializer.FromJson(Data, typeof(OrderMaster));
            String Data2 = eventArgument.Split('■')[2];
            List<Discount> discountList = (List<Discount>)ObjectSerializer.FromJson(Data2, typeof(List<Discount>));
            List<Discount> discountListFinal = new List<Discount>();
            foreach (Discount discount_Filter in discountList)
            {
                discount_Filter.Company = new Company();
                discount_Filter.Company.ID = _companyID;
                List<Discount> discountListResult = CDADiscount.Select(discount_Filter, false);
                if (discountListResult.Count > 0)
                {
                    discountListFinal.Add(discountListResult.First());
                }
            }

            orderMaster.Company = new Company();
            orderMaster.Company.ID = _companyID;
            orderMaster.OrderType = new OrderType();
            orderMaster.OrderType.ID = cnstOrderType.ONL;
            orderMaster.User = new User();
            orderMaster.User.ID = (int)cnstDatabase.DBOperationResult.NullValue;
            
            if (CBLOrderMaster.InsertOrder(orderMaster, discountListFinal, out ErrorMessage))
                CallBackResult = "saveOrderSuccess■" + "Your order saved successfully";
            else
                CallBackResult = "saveOrderError■" + ErrorMessage;
        }
    }
    #endregion
}
 